# cf/serializers.py
from rest_framework import serializers
from .models import CFUser, Submission, DailyStats


class CFUserSerializer(serializers.ModelSerializer):
    """CF用户序列化器"""

    class Meta:
        model = CFUser
        fields = ['id', 'username', 'handle', 'is_active', 'created_at', 'last_updated']
        read_only_fields = ['id', 'created_at', 'last_updated']


class SubmissionSerializer(serializers.ModelSerializer):
    """提交记录序列化器"""
    user = serializers.StringRelatedField()
    tags_list = serializers.SerializerMethodField()

    class Meta:
        model = Submission
        fields = [
            'id', 'user', 'submission_id', 'contest_id', 'problem_index',
            'problem_name', 'programming_language', 'verdict', 'creation_time',
            'submission_time', 'tags', 'tags_list'
        ]
        read_only_fields = ['id']

    def get_tags_list(self, obj):
        """获取标签列表"""
        return obj.get_tags_list()


class DailyStatsSerializer(serializers.ModelSerializer):
    """每日统计序列化器"""
    user = serializers.StringRelatedField()
    unique_problems_list = serializers.SerializerMethodField()
    acceptance_rate = serializers.SerializerMethodField()

    class Meta:
        model = DailyStats
        fields = [
            'id', 'user', 'date', 'total_submissions', 'accepted_submissions',
            'problems_solved', 'unique_problems', 'unique_problems_list', 'acceptance_rate'
        ]
        read_only_fields = ['id']

    def get_unique_problems_list(self, obj):
        """获取独特问题列表"""
        return obj.get_unique_problems_list()

    def get_acceptance_rate(self, obj):
        """计算通过率"""
        if obj.total_submissions > 0:
            return round((obj.accepted_submissions / obj.total_submissions) * 100, 2)
        return 0


class UpdateResultSerializer(serializers.Serializer):
    """更新结果序列化器"""
    success = serializers.BooleanField()
    username = serializers.CharField(required=False, allow_blank=True)
    today_submissions_count = serializers.IntegerField(required=False, allow_null=True)
    saved_submissions_count = serializers.IntegerField(required=False, allow_null=True)
    daily_stats_updated = serializers.BooleanField(required=False, allow_null=True)
    date = serializers.CharField(required=False, allow_blank=True)
    error = serializers.CharField(required=False, allow_blank=True)
    total_submissions_count = serializers.IntegerField(required=False, allow_null=True)
    message = serializers.CharField(required=False, allow_blank=True)


class BulkUpdateResultSerializer(serializers.Serializer):
    """批量更新结果序列化器"""
    success = serializers.BooleanField()
    message = serializers.CharField(required=False, allow_blank=True)
    results = UpdateResultSerializer(many=True, required=False)